package com.ecotope.quartz.module.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ecotope.quartz.module.entity.AccessData;
import com.ecotope.quartz.module.entity.AtmosphericStation;
import com.ecotope.quartz.module.entity.TownAtmosphericStation;
import com.ecotope.quartz.module.opentsdb.ExpectResponse;
import com.ecotope.quartz.module.opentsdb.HttpClientImpl;
import com.ecotope.quartz.module.opentsdb.builder.MetricBuilder;
import com.ecotope.quartz.module.opentsdb.response.Response;
import com.ecotope.quartz.module.service.AccessDataService;
import com.ecotope.quartz.module.service.AtmosphericStationService;
import com.ecotope.quartz.module.service.TownAtmosphericStationService;
import com.ecotope.quartz.module.util.DateUtil;
import com.ecotope.quartz.module.util.HttpURLConnectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@EnableAsync
@EnableScheduling
@SuppressWarnings("all")
public class WeekAtmosphereSchedule {


    //省平台地址
    private String baseUrl = "http://59.202.42.88:8180/sjmh/dynamicservice/dynamicquery";

    //大气乡镇
    private final static String getDataQTownByxzqh = "http://10.33.70.133:6081/rest/api/foreign/getDataQTown";

    //页大小
    private Integer pageSize = 10000;

    //页码
    private Integer pageNum = 1;

    //QX
    private String fwxhQx = "f9fa13d4b3f2411fac31cb0c38de39a9";
    private String keyQx = "812e655c-2d94-4a6f-af24-5074868eb502";

    @Autowired
    private AccessDataService accessDataService;

    /**
     * QX 清新空气
     */
    @Scheduled(cron = "0 0 1 ? * 2")
    @Async
    public void getQXDateAndInsertOpentsdb() {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
        Date date = new Date();
        String JSSJ = df.format(date);

        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd 00");
        Date dateNew = date;
        Calendar calendarNew = Calendar.getInstance();
        calendarNew.setTime(dateNew);
        calendarNew.add(Calendar.DATE, -7);
        dateNew = calendarNew.getTime();
        String KSSJ = df.format(dateNew);

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        //清新空气站点请求地址——省平台
        while (true) {
            try {
                String kssj = URLEncoder.encode(KSSJ, "utf-8");
                String jssj = URLEncoder.encode(JSSJ, "utf-8");
                String url = baseUrl + "?fwxh=" + fwxhQx + "&key=" + keyQx + "&pagenum=" + pageNum + "&pageSize=" + pageSize + "&KSSJ=" + kssj + "&JSSJ=" + jssj;
                String methodReturn = HttpURLConnectionUtil.getMethod(url);
                if (HttpURLConnectionUtil.isJsonObject(methodReturn)) {
                    JSONObject jsonObject = JSONObject.parseObject(methodReturn);
                    JSONObject data = jsonObject.getJSONObject("data");
                    String qxkqzdxssjDay = data.getString("QXKQZDXSSJ");

                    if (qxkqzdxssjDay != null && !qxkqzdxssjDay.equals("[]")) {
                        log.info("insert qx-opentsdb data start:");
                        //mysql数据库 记录数据插入时间
                        AccessData accessData = AccessData.builder().type(3).url("小时数据===>" + KSSJ + "--" + JSSJ).data("清新空气周数据").build();
                        accessDataService.insert(accessData);
                        //插入opentsdb
                        JSONArray jsonArray = JSONArray.parseArray(qxkqzdxssjDay);
                        for (Object o : jsonArray) {
                            Map map = JSONObject.parseObject(o.toString(), Map.class);
                            if (map.size() > 0) {
                                //移除不必要的数据
                                map.remove("CJSJ");
                                map.remove("XGSJ");
                                map.remove("XH");
                                map.remove("PXH");
                                map.remove("BZ");
                                //数据标记
                                DateUtil.SJBJMap(map);

                                String yzbh = String.valueOf(map.get("YZBH"));
                                map.remove("YZBH");
                                String sjbj = String.valueOf(map.get("SJBJ"));
                                map.remove("SJBJ");
                                //转换时间戳
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                if (map.get("JCSJ") != null) {
                                    long timestamp = sdf.parse(String.valueOf(map.get("JCSJ"))).getTime();
                                    String host = String.valueOf(map.get("ZDBH"));
                                    MetricBuilder builder = MetricBuilder.getInstance();
                                    map.remove("JCSJ");
                                    map.remove("ZDBH");
                                    for (Object entry : map.entrySet()) {
                                        Map.Entry<String, Object> map1 = (Map.Entry<String, Object>) entry;
                                        Double value = null;
                                        if ("--".equals(map1.getValue()) || StringUtils.isEmpty((String) map1.getValue())) {
                                            value = 0.0;
                                        } else {
                                            value = Double.parseDouble(String.valueOf(map1.getValue()));
                                        }
                                        builder.addMetric("mete.air").setDataPoint(timestamp, value).addTag("yzbh", yzbh)
                                                .addTag("sjbj", sjbj).addTag("host", host).addTag("index", map1.getKey().toLowerCase());
                                    }
                                    //存入opentsdb
                                    Response response = client.pushMetrics(builder,
                                            ExpectResponse.SUMMARY);
                                    if (!response.isSuccess()) {
                                        log.info("insertopentsdb data fail! map is null!");
                                    }
                                }
                            }
                        }
                        pageNum++;
                        log.info("insert qx-opentsdb data end");
                    } else {
                        log.info("返回数据为空");
                        AccessData accessData = AccessData.builder().type(3).url("返回数据为空" + KSSJ + "--" + JSSJ).data("清新空气周数据").build();
                        accessDataService.insert(accessData);
                        break;
                    }
                } else {
                    log.info(methodReturn);
                    AccessData accessData = AccessData.builder().type(3).url(methodReturn + KSSJ + "--" + JSSJ).data("清新空气周数据").build();
                    accessDataService.insert(accessData);
                    Thread.sleep(1000 * 60 * 6);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
